package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import com.example.xcService.pojo.tool.StringTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 福禄接口
 * **/
@Slf4j
public class Plugin_ECARD_P010 implements ChannelService {
    public ChannelResult QueryBalance(JSONObject apiConfig){
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    public  ChannelResult Submit(JSONObject apiConfig, Map<String,Object> data){

        try {

            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));


            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("buy_num",1);
            dataParams.put("charge_account",dataConfig.getString("AccountVal"));
            dataParams.put("product_id",dataConfig.getString("SUPProductId"));
            dataParams.put("customer_order_no",dataConfig.getString("ChannelOrderCode"));

            String biz_content=JSONObject.toJSONString(dataParams);
            DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String timestamp=dtf.format(LocalDateTime.now());

            Map rqParams = new LinkedHashMap<String, String>();
            rqParams.put("app_key",apiConfig.getString("USERID"));
            rqParams.put("method","fulu.order.direct.add");
            rqParams.put("timestamp",timestamp);
            rqParams.put("version","2.0");
            rqParams.put("format","json");
            rqParams.put("charset","utf-8");
            rqParams.put("sign_type","md5");
            rqParams.put("app_auth_token","");
            rqParams.put("biz_content",biz_content);



            String jsonData = JSONObject.toJSONString(rqParams);
            char[] StringToChar=jsonData.toCharArray();
            Arrays.sort(StringToChar);
            String sstr=new String(StringToChar)+apiConfig.getString("SecretKey");
            String sign=StringTool.stringToMD5(sstr).toLowerCase();
            rqParams.put("sign",sign);



            String url=apiConfig.getString("SubmitURL");

            String responseContent = sendPost(url,rqParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("code");
            String msg = retobj.getString("message");
            if (code.equals("0")) {
                JSONObject robj =retobj.getJSONObject("result");
                String order_state = robj.getString("order_state");
                if ("untreated".equals(order_state) || "success".equals(order_state) || "processing".equals(order_state)){
                    return ChannelResult.IN_PROCESS();
                }else if ("failed".equals(order_state)){
                    return ChannelResult.FAILED(code+","+msg);
                }
                return ChannelResult.error(order_state);
            }else if (code.equals("4010")){
                return ChannelResult.IN_PROCESS();
            }else {
                return ChannelResult.FAILED(code+","+msg);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("福禄提交订单接口错误：",ex);
            return  ChannelResult.error("福禄提交订单接口错误");
        }
    }

    public  ChannelResult Query(JSONObject apiConfig,Map<String,Object> data) {
        try {



            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("customer_order_no",dataConfig.getString("ChannelOrderCode"));

            String biz_content=JSONObject.toJSONString(dataParams);
            DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String timestamp=dtf.format(LocalDateTime.now());

            Map rqParams = new LinkedHashMap<String, String>();
            rqParams.put("app_key",apiConfig.getString("USERID"));
            rqParams.put("method","fulu.order.info.get");
            rqParams.put("timestamp",timestamp);
            rqParams.put("version","2.0");
            rqParams.put("format","json");
            rqParams.put("charset","utf-8");
            rqParams.put("sign_type","md5");
            rqParams.put("app_auth_token","");
            rqParams.put("biz_content",biz_content);



            String jsonData = JSONObject.toJSONString(rqParams);
            char[] StringToChar=jsonData.toCharArray();
            Arrays.sort(StringToChar);
            String sstr=new String(StringToChar)+apiConfig.getString("SecretKey");
            String sign=StringTool.stringToMD5(sstr).toLowerCase();
            rqParams.put("sign",sign);



            String url = apiConfig.getString("QueryURL");
            String responseContent = sendPost(url, rqParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("code");
            String msg = retobj.getString("message");
            if (code.equals("0")) {
                JSONObject robj =retobj.getJSONObject("result");
                String order_state = robj.getString("order_state");
                if ("success".equals(order_state)){
                    return  ChannelResult.success("success");
                }
                else if ("untreated".equals(order_state)  || "processing".equals(order_state)){
                    return ChannelResult.IN_PROCESS();
                }else if ("failed".equals(order_state)){
                    return ChannelResult.FAILED(code+","+msg);
                }
                return ChannelResult.error(order_state);
            }else {
                return ChannelResult.error(code+","+msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("福禄查询订单接口错误：", ex);
            return ChannelResult.error("福禄查询订单接口错误");
        }
    }

    public  ChannelResult Notify(JSONObject apiConfig, Map<String,Object> data){
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");

    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String,String> param) {
        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(param),"utf-8"));
            log.info("httpPost请求："+url+"?"+JSONObject.toJSONString(param));
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result= EntityUtils.toString(responseEntity);
                log.info("httpPost请求返回："+JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }
}
